﻿using MediatR;
using Medical.Api.Write.Application.Command.RecyclingCleaning.Disinfects;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.Extensions.Logging;

namespace Medical.Api.Write.Application.Handler.RecyclingCleaning.Disinfects
{
    /// <summary>
    /// 修改消毒状态信息命令处理
    /// </summary>
    public class UpdateDisinfectionStateCommandHandlter : IRequestHandler<UpdateDisinfectionStateCommand, ApiResult<int>>
    {
        /// <summary>
        /// 消毒登记仓储
        /// </summary>
        private readonly IBaseRepository<DisinfectionRegistration> _disinfectionRegistrationRepository;

        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<UpdateDisinfectionStateCommandHandlter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="disinfectionRegistrationRepository">消毒登记仓储</param>
        /// <param name="logger">日志记录器</param>
        public UpdateDisinfectionStateCommandHandlter(
            IBaseRepository<DisinfectionRegistration> disinfectionRegistrationRepository,
            ILogger<UpdateDisinfectionStateCommandHandlter> logger)
        {
            _disinfectionRegistrationRepository = disinfectionRegistrationRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改消毒状态命令
        /// </summary>
        /// <param name="request">修改消毒状态命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateDisinfectionStateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理消毒状态更新，ID：{Id}，新状态：{State}", request.Id, request.State);

                // 检查要修改的消毒登记记录是否存在
                var existingDisinfection = await _disinfectionRegistrationRepository.GetModelAsync(request.Id);
                if (existingDisinfection == null)
                {
                    _logger.LogWarning("未找到ID为{Id}的消毒登记记录", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.Id}的消毒登记记录"
                    };
                }

                // 检查记录是否已被删除
                if (existingDisinfection.IsDeleted)
                {
                    _logger.LogWarning("ID为{Id}的消毒登记记录已被删除", request.Id);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"ID为{request.Id}的消毒登记记录已被删除"
                    };
                }

                // 更新消毒状态
                existingDisinfection.Status = request.State;
                existingDisinfection.UpdateTime = DateTime.Now;

                // 如果状态为已完成，设置完成时间
                if (request.State == 1)
                {
                    existingDisinfection.CompletionTime = DateTime.Now;
                }

                // 更新消毒登记记录
                var updateResult = _disinfectionRegistrationRepository.Update(existingDisinfection);

                if (updateResult > 0)
                {
                    _logger.LogInformation("成功更新消毒状态，ID：{Id}，新状态：{State}", request.Id, request.State);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Success,
                        Data = request.Id,
                        Msg = "成功更新消毒状态"
                    };
                }
                else
                {
                    _logger.LogWarning("更新消毒状态失败，ID：{Id}，新状态：{State}", request.Id, request.State);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Data = 0,
                        Msg = "更新消毒状态失败"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新消毒状态时发生异常，ID：{Id}，新状态：{State}", request.Id, request.State);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Data = 0,
                    Msg = $"更新消毒状态异常：{ex.Message}"
                };
            }
        }
    }
}
